package com.heima.wemedia.service.Imp;



import com.alibaba.fastjson.JSON;
import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.common.constants.message.PublishArticleConstants;
import com.heima.model.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.AutoScanWmNewsService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service

public class WmNewsAutoScanServiceImpl implements AutoScanWmNewsService {
    @Autowired
    private AdminFeign adminFeign;
    @Autowired
    private GreenScan greenScan;
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Value("${file.oss.web-site}") //直接从配置中动态读取
    String webSite;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * 文章审核
     *
     * @param id
     */
    @GlobalTransactional
    @Override
    public void autoScanWmNews(Integer id) {
        //1.校验数据
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "id不能为空!");
        }
        //2.先查询文章是否存在 再根据id获得文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "需要审核的文章不存在");
        }
        //判断文章的状态是否是待审核状态
        if (!WemediaConstants.WM_NEWS_SUMMIT_STATUS.equals(wmNews.getStatus())) {
            log.info("当前文章审核状态为{} 不是审核状态，无需审核", wmNews.getStatus());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章不是审核状态");
        }
        //3.获取文章中的文字  图片
        Map<String, Object> map = parseImageAndText(wmNews);
        //4.进行敏感词验证
        boolean textFlag = handleTextScan(map.get("content"),wmNews);
        //存在敏感词
        if (!textFlag) {
            log.info("文章中有敏感词");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章中有敏感词");
        }
        //文本违规阿里云安全校验
        boolean textScan =  handleText(map.get("content"),wmNews);
        if (!textScan) {
            //返回结果为false内容违规
            log.info("内容违规");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"内容违规");
        }
        //图片违规阿里云安全校验
        List<String> images =  (List<String>)map.get("images");
        //图片不为空判断
        if (!CollectionUtils.isEmpty(images)) {
            boolean imageScan = handelImage(images,wmNews);
            if (!imageScan) {
                //返回结果为false内容违规
                log.info("图片内容违规");
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"图片内容违规");
            }
        }
        // 8. 将文章状态改为 8 自动审核通过
        updateWmNews(WmNews.Status.SUCCESS.getCode(), "审核通过",wmNews);
        //9.文章审核通过 自动发布
        //9.1计算延迟时间
        long publishTime = wmNews.getPublishTime().getTime();
        long curTime = new Date().getTime();
        long delayTime = publishTime - curTime;
        //注入rabbitmq的客户端 向mq发送消息
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE, //参数1：交换机
                PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY,  //参数2：路由关键字
                wmNews.getId(),  //参数3：传递字段
                message -> { //
            message.getMessageProperties().setHeader("x-delay",delayTime<=0?0:delayTime);
            return message;
                });
       log.info("发布文章通知成功发送 文章id{}",wmNews.getId());
    }

    private boolean handelImage(List<String> images, WmNews wmNews) {
        boolean flag = false;
        try {
            ScanResult scanResult = greenScan.imageUrlScan(images);
            switch (scanResult.getSuggestion()){
                case "block":
                    // 失败
                    updateWmNews(WmNews.Status.FAIL.getCode(), "文章图片中违规信息: "+scanResult.getLabel() ,wmNews);
                    break;
                case "review":
                    // 人工
                    updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "文章图片中有不确定因素，需要进一步人工审核" ,wmNews);
                    break;
                case "pass":
                    // 成功
                    flag = true;
                    break;
                default:
                    // 人工
                    updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "阿里云调用状态异常，需要进一步人工审核:" ,wmNews);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "阿里云调用失败，需要进一步人工审核:" ,wmNews);
        }
        return flag;
    }


    /**
     * 对文本进行违规查询
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleText(Object content, WmNews wmNews) {
        boolean flag = false;
        try {
            ScanResult scanResult = greenScan.greenTextScan((String) content);
            String suggestion = scanResult.getSuggestion();
            switch (suggestion) {
                case "block":
                    // 失败
                    updateWmNews(WmNews.Status.FAIL.getCode(), "文章内容中包含违规词汇: "+scanResult.getLabel() ,wmNews);
                    break;
                case "review":
                    // 人工
                    updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "文章内容中有不确定因素，需要进一步人工审核:" ,wmNews);
                    break;
                case "pass":
                    // 成功
                    flag = true;
                    break;
                default:
                    // 人工
                    updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "阿里云调用状态异常，需要进一步人工审核:" ,wmNews);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 人工
            updateWmNews(WmNews.Status.ADMIN_AUTH.getCode(), "阿里云调用失败，需要进一步人工审核:" ,wmNews);
        }
        return flag;
    }

    //对敏感词进行验证
    private boolean handleTextScan(Object context,WmNews wmNews) {
        //远程调用获得本文中的敏感词
        ResponseResult<List<String>> responseResult = adminFeign.findSensitiveList();
        //判断远程调用是否成功
        if (!responseResult.checkCode()) {
            log.info("远程调用失败");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用失败");
        }
        //对文本的敏感词进行封装
        List<String> sensitives = responseResult.getData();
        SensitiveWordUtil.initMap(sensitives);
        //校验
        String contentMsg = (String) context;
        Map<String, Integer> map = SensitiveWordUtil.matchWords(contentMsg);
        if (!CollectionUtils.isEmpty(map)) {
            //如果存在敏感词 我们将文章状态修改为2
            updateWmNews(WmNews.Status.FAIL.getCode(), "文章中包含敏感词: "+map ,wmNews);
            return false;
        }
        return true;
    }
    //如果存在敏感词修改文章的状态为2 设置原因 传入对象
    private void updateWmNews(short status, String reason, WmNews wmNews) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    //获取文章中的文本和图片
    private Map<String, Object> parseImageAndText(WmNews wmNews) {
        //判断传入的参数不为空
        String contentJson = wmNews.getContent();
        if (StringUtils.isBlank(contentJson) || StringUtils.isBlank(wmNews.getTitle())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章标题或内容内容不能为空");
        }
        //将json数据转化为list<map>集合
        List<Map> contentMapList = JSON.parseArray(contentJson, Map.class);
        //1.获取文章中的文本信息
        String content = contentMapList.stream()
                .filter(m -> "text".equals(m.get("type")))
                .map(map -> map.get("value").toString())
                .collect(Collectors.joining("_hmtt_"));
        //拼接标题拿到完整的字符文本
        content = wmNews.getTitle() + "_hmtt_" + content;
        //2.获取图片的集合
        //获取内容中的图片内容
        List<String> images = contentMapList.stream()
                .filter(m -> "image".equals(m.get("type")))
                .map(map -> map.get("value").toString())
                .collect(Collectors.toList());
        //获取封面中的图片
        String coverImages = wmNews.getImages();
        if (StringUtils.isNotBlank(coverImages)) {
            String[] coverImagesList = coverImages.split(",");
            List<String> coverList = Arrays.stream(coverImagesList)
                    .map(url ->webSite +  url)
                    .collect(Collectors.toList());
            //将封面存入
            images.addAll(coverList);
        }
        //创建封装图片和信息的集合
        HashMap<String, Object> map = new HashMap<>();
        images = images.stream()
                .distinct()
                .collect(Collectors.toList());
        map.put("images",images);
        map.put("content",content);
        return map;
    }
}
